/**   
 * @Title: CountExample1.java 
 * @Package com.liumm.concurrently.example 
 * @Description: TODO
 * @author liumm   
 * @date 2018年4月18日 下午9:50:23 
 * @version V1.0   
 */
package com.liumm.concurrently.example.count;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

import com.liumm.concurrently.annoations.ThreadSafe;

import lombok.extern.slf4j.Slf4j;

/** 
 * @ClassName: CountExample2
 * @Description: 计数线程安全
 * @author liumm 
 * @date 2018年4月18日 下午9:50:23 
 *  
 */
@Slf4j
@ThreadSafe
public class CountExample3 {

	private static int clientTotal = 5000;

	private static int threadTotal = 50;

	private static Integer count = 0;

	public static void main(String[] args) throws InterruptedException {

		ExecutorService threadPool = Executors.newCachedThreadPool();
		final Semaphore semaphore = new Semaphore(threadTotal);
		final CountDownLatch downLatch = new CountDownLatch(clientTotal);
		for (int i = 0; i < clientTotal; i++) {
			threadPool.execute(() -> {
				try {
					semaphore.acquire();
					add();
					semaphore.release();
				} catch (InterruptedException e) {
					log.error("Exception", e);
				}
				downLatch.countDown();
			});
		}
		downLatch.await();
		threadPool.shutdown();
		log.info("count:{}", count);
	}

	private synchronized static void add() {
		count++;
	}

}
